<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="关键字" prop="keyName">
        <el-input v-model="queryParams.keyName" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <!-- todo -->
      <el-form-item label="上级分类" prop="parentId">
        <el-select
      v-model="queryParams.parentId"
      placeholder="请选择..."
      size="mini"
      clearable
      ref="select"
      style="width: 300px"
    >
     
      <!-- // 设置一个隐藏的下拉选项，选项显示的是汉字label，值是value
      // 如果不设置一个下拉选项，下面的树形组件将无法正常使用 -->
      <el-option hidden key="id" :value="queryParams.parentId" :label="selectName">
      </el-option>
      <el-tree
        :data="categoryOptions"
        :props="defaultProps"
        @node-click="handleNodeClick"
        :expand-on-click-node="false"
        ref="tree"
        node-key="id"
        :default-expand-all="true"
      >
        <span slot-scope="{ data }">  
          <span>{{ data.label }}</span>
        </span>
      </el-tree>
    </el-select>

      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['businessManagement:category:add']">添加分类</el-button>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="categoryList" @selection-change="handleSelectionChange">
      <el-table-column type="index" align="center" label="序号" />
      <el-table-column label="上级分类" align="center" prop="parentId" :formatter="getcategoryById" />
      <el-table-column label="分类名称" align="center" prop="categoryName" />
      <el-table-column label="描述" align="center" prop="categoryDesc" />


      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['businessManagement:category:edit']">编辑</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['businessManagement:category:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改物品分类信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="上级分类" prop="parentId">
        <el-select
      v-model="form.parentId"
      placeholder="请选择..."
      size="mini"
      clearable
      ref="select"
      style="width: 300px"
    >
     
      <!-- // 设置一个隐藏的下拉选项，选项显示的是汉字label，值是value
      // 如果不设置一个下拉选项，下面的树形组件将无法正常使用 -->
      <el-option hidden key="id" :value="form.parentId" :label="selectName">
      </el-option>
      <el-tree
        :data="categoryOptions"
        :props="defaultProps"
        @node-click="handleNodeClick"
        :expand-on-click-node="false"
        ref="tree"
        node-key="id"
        :default-expand-all="true"
      >
        <span slot-scope="{ data }">  
          <span>{{ data.label }}</span>
        </span>
      </el-tree>
    </el-select>

      </el-form-item>
        <el-form-item label="分类名称" prop="categoryName">
          <el-input v-model="form.categoryName" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="描述" prop="categoryDesc">
          <el-input type="textarea" rows="5" v-model="form.categoryDesc" placeholder="请输入描述">
          </el-input>

        </el-form-item>
        
        
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">立即提交</el-button>
        <el-button @click="cancel">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCategory,listCategorys, getCategory, delCategory, addCategory, updateCategory, categoryTreeselect } from "@/api/businessManagement/category";

export default {
  name: "Category",
  data() {
    return {
      // 所有的分类信息
      categorys: [],
      selectVal: "", // select框的绑定值
      selectName: "", // select框显示的name
      treeFilter: "", // 搜索框绑定值，用作过滤
      defaultProps: {
        children: "children",
        label: "name",
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 物品分类信息表格数据
      categoryList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        keyName: null,
        parentId: null,

      },
      // 物品分类信息下拉树结构数据
      categoryOptions: [],
      // 表单参数
      form: {
        parentId : null,
        categoryName: null,
        categoryDesc: null,
      },
      // 表单校验
      rules: {
        categoryName: [
          { required: true, message: "名称不能为空", trigger: "blur" },
          {
            pattern: /^.{0,50}$/,
            message: "名称不能超30个字符", trigger: "blur"
          }
        ],
       
        categoryDesc: [
          {
            pattern: /^.{0,50}$/,
            message: "描述不能超200个字符", trigger: "blur"
          }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  watch: {
    value(){
      this.valueId = this.value
      this.initHandle()
    }
  },
  methods: {
    // 根据分类id获取名字
    getcategoryById(row) {
      
      let categoryName = '';
      for (let category of this.categorys) {
        if (category.id == row.parentId) {
          categoryName = category.categoryName;
        }
      }
      return categoryName;
    },

    // 结构树点击事件
    handleNodeClick(data) {
          this.queryParams.parentId = data.id; // select绑定值为点击的选项的value
          this.form.parentId = data.id; // select绑定值为点击的选项的value
          this.selectName = data.label; // input中显示值为label
          this.$refs.select.blur(); // 点击后关闭下拉框，因为点击树形控件后select不会自动折叠
        },


    /** 查询分类树结构 */
    getCategoryTreeselect() {
      categoryTreeselect().then(response => {
        this.categoryOptions = response.data;
      });
    },

    /** 查询物品分类信息列表 */
    getList() {
      this.loading = true;
      listCategory(this.queryParams).then(response => {
        this.categoryList = response.rows;
        this.total = response.total;
        this.loading = false;
      });

      this.getCategoryTreeselect();
      // 获取所有的分类信息
      listCategorys().then(resp => {
        this.categorys = resp.data;
      })
    },
    // 取消按钮
    cancel() {
      this.selectName = null;
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        categoryName: null,
        categoryDesc: null,
        busiPath: null,
        parentId: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.selectName = null;
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加物品分类信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.form = row
     
      this.title = "修改物品分类信息";
      for (let category of this.categorys) {
        if (category.id == row.parentId) {
          this.selectName = category.categoryName;
        }
      }
      this.open = true;
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateCategory(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              
            });
          } else {

            addCategory(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              
            });
          }
          this.selectName = null;
          this.queryParams.parentId = null;
          this.form.parentId = null;
          this.getList();
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      
      this.$modal.confirm('是否确认删除物品分类信息编号为"' + row.id + '"的数据项？').then(function () {
        return delCategory(row.id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    }
   
  }
};
</script>
